package portal.bean;


import java.io.IOException;

import java.io.PrintStream;

import java.lang.reflect.Field;

import java.net.URL;
import java.net.URLConnection;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.TimeZone;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import javax.portlet.PortletRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.layout.RichPanelBorderLayout;
import oracle.adf.view.rich.component.rich.nav.RichCommandLink;
import oracle.adf.view.rich.component.rich.output.RichOutputText;
import oracle.adf.view.rich.context.AdfFacesContext;

import oracle.stellent.ridc.IdcClient;
import oracle.stellent.ridc.IdcClientException;
import oracle.stellent.ridc.IdcContext;
import oracle.stellent.ridc.model.DataBinder;
import oracle.stellent.ridc.model.DataObject;
import oracle.stellent.ridc.model.DataResultSet;
import oracle.stellent.ridc.model.impl.DataResultSetRow;
import oracle.stellent.ridc.protocol.ServiceResponse;

import oracle.webcenter.content.integration.BinaryValue;
import oracle.webcenter.content.integration.ContentContext;
import oracle.webcenter.content.integration.ID;
import oracle.webcenter.content.integration.Node;
import oracle.webcenter.content.integration.Property;
import oracle.webcenter.content.integration.RepositoryException;
import oracle.webcenter.content.integration.Value;
import oracle.webcenter.content.integration.el.support.ValueWrapperImpl;
import oracle.webcenter.content.integration.federated.ContentManagerFactory;
import oracle.webcenter.content.integration.federated.INodeManager;
import oracle.webcenter.content.integration.federated.internal.ContentContextHelper;
import oracle.webcenter.content.integration.federated.internal.delegate.IUCMContext;
import oracle.webcenter.doclib.internal.model.presenter.conf.PresenterConfigurationException;
import oracle.webcenter.doclib.internal.model.presenter.conf.PresenterDatasource;
import oracle.webcenter.doclib.internal.model.presenter.conf.QueryDatasource;
import oracle.webcenter.doclib.internal.model.presenter.conf.ResultsetConfig;
import oracle.webcenter.doclib.internal.model.presenter.conf.SearchCriterion;
import oracle.webcenter.doclib.internal.model.presenter.conf.SortCriterion;
import oracle.webcenter.doclib.internal.view.presenter.ContentPresenter;
import oracle.webcenter.doclib.internal.view.presenter.ContentPresenterWizard;
import oracle.webcenter.doclib.internal.view.presenter.conf.PresenterConfiguration;
import oracle.webcenter.doclib.internal.view.presenter.conf.PresenterConfigurationData;
import oracle.webcenter.framework.view.JSFUtils;
import oracle.webcenter.navigationframework.NavigationResource;
import oracle.webcenter.portalframework.sitestructure.SiteStructure;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.myfaces.trinidad.component.UIXIterator;
import org.apache.myfaces.trinidad.model.SortableModel;
import org.apache.myfaces.trinidadinternal.taglib.util.MethodExpressionMethodBinding;

import portal.Global;
import portal.UtilsContent;


public class Contentbean {

    private SortableModel lstObjectNode = null;
    private int contentpresenterMaxresult;
    private String imgcontent = "";
    private String connectionName;
    private String pagedetailUrl;
    private String individualpagedetailUrl;
    private String pageListAllUrl;
    private String tempara;
    private boolean hasDicriptionImage = false;
    private String newscontent = null;
    private List<DataObject> lstReferentNodes;
    private SortableModel lstNews;
    private List<DataObject> templstNews;
    private boolean templst2x = false;
    private boolean templst2x2 = false;
    private List<String> pagesnumber = new ArrayList<String>();
    private String newsDetailTitle;
    private int currentPage = 1;
    private int selectedPage = 1;
    private int numberOfPage = -1;
    private boolean firstrequest = true;
    private int numberOfResult = 0;
    private String functionrequest = "";
    private int counter = 0;
    private Date ngayxuatban;
    private String chuyenmuctin;
    private String chuyenmuctinID;
    private UIXIterator iteratorNodes;
    private boolean hasnextpage;
    private RichPanelBorderLayout pagingPanelBorderLayout;
    private RichInputText inputDetailPath;
    private RichInputText inputlPageListAllPath;
    private String currentrequestURL;
    private String totalRows = "0";
    private TimeZone timezone = TimeZone.getTimeZone("GMT+7");
    private List<DataObject> lstAttachFile = new ArrayList<DataObject>();
    private boolean hasAttachFile = false;
    private String initListContent;
    private List<DataObject> lstLienketGroup = new ArrayList<DataObject>();
    private List<DataObject> lstLienket = new ArrayList<DataObject>();
    private static final String DEFAULT_LANGCODE = "vi";
    private RichInputText inputGroupID;
    private boolean hasOldDicriptionImage;

    public Contentbean() {

    }

    private String currentRequestUrl() {
        String url = "";
        HttpServletRequest request =
            (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        url =
request.getRequestURI().replaceFirst(request.getContextPath(), "");
        return url;
    }

    /**
     * @creator
     * @comment
     * @param sortField
     * @param b
     * @return
     */
    private SortableModel listObjecNode(String sortField, boolean b) {
        SortableModel lst = null;
        try {
            String expression = "#{nodes}";
            SortableModel result =
                (SortableModel)JSFUtils.resolveExpression(expression);
            int blean = result.getSortCriteria().size();
            List<Node> lstNode = (List<Node>)result.getWrappedData();
            String url =
                FacesContext.getCurrentInstance().getExternalContext().getRequestServletPath();
            Node node = lstNode.get(0);
            String kieutin;
            try {
                kieutin =
                        node.getProperty("xmKieutintuc").getValue().toString();
            } catch (RepositoryException e) {
            }
            int c = result.getRowCount();
            List<org.apache.myfaces.trinidad.model.SortCriterion> lstsrc =
                new ArrayList();
            if (sortField != null && sortField.length() > 0) {
                org.apache.myfaces.trinidad.model.SortCriterion src =
                    new org.apache.myfaces.trinidad.model.SortCriterion(sortField,
                                                                        b);
                lstsrc.add(src);
                result.setSortCriteria(lstsrc);
            }
            lst = result;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return lst;
    }

    /**
     * @comment lay url cua trang hien thi chi tiet noi dung
     * @return
     */
    private String detailPageUrl() {
        String pageurl = "";
        String elexp = "#{navigationContext.defaultNavigationModel}";
        SiteStructure str = (SiteStructure)JSFUtils.resolveExpression(elexp);
        List<NavigationResource> lstnavresources;
        try {
            if (inputDetailPath != null &&
                inputDetailPath.getValue() != null) {
                String strparentpath = inputDetailPath.getValue().toString();
                //elexp = "#{node.propertyMap['xmChuyenmuctin'].value}";
                //Object obj = (Object)JSFUtils.resolveExpression(elexp);
                String strChuyenmuc =
                    strparentpath.substring(strparentpath.lastIndexOf("/") + 1,
                                            strparentpath.length());
                strparentpath =
                        strparentpath.substring(0, strparentpath.lastIndexOf("/"));
                lstnavresources = str.getResource(strparentpath).getChildren();
                for (NavigationResource nav1 : lstnavresources) {
                    for (NavigationResource nav2 : nav1.getChildren()) {
                        if (nav2.getChildCount() > 0) {
                            for (NavigationResource nav3 :
                                 nav2.getChildren()) {
                                if (nav3.getChildCount() > 0) {
                                    for (NavigationResource nav4 :
                                         nav3.getChildren()) {
                                        if (nav4.getChildCount() > 0) {
                                            for (NavigationResource nav5 :
                                                 nav4.getChildren()) {
                                                if (nav5.getPrettyUrl().contains(strChuyenmuc)) {
                                                    pageurl =
                                                            nav5.getPrettyUrl();
                                                    break;
                                                }
                                            }
                                        } else {
                                            if (nav4.getPrettyUrl().contains(strChuyenmuc)) {
                                                pageurl = nav4.getPrettyUrl();
                                                break;
                                            }
                                        }
                                        if (pageurl.length() > 0)
                                            break;

                                    }
                                } else {
                                    if (nav3.getPrettyUrl().contains(strChuyenmuc)) {
                                        pageurl = nav3.getPrettyUrl();
                                        break;
                                    }
                                }

                                if (pageurl.length() > 0)
                                    break;
                            }
                        } else {

                            if (nav2.getPrettyUrl().contains(strChuyenmuc)) {
                                pageurl = nav2.getPrettyUrl();
                                break;
                            }
                        }
                        if (pageurl.length() > 0)
                            break;
                    }
                    if (pageurl.length() > 0)
                        break;
                }
            }
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return pageurl;

    }

    /**
     * @creator TuyenNT
     * @comment Lay url cua trang danh sach xem tat ca tin
     * @return  URL cua trang danh sach xem tat ca tin
     */
    private String listAllPageUrl() {
        String strurl = "";
        String elexp = "#{navigationContext.defaultNavigationModel}";
        SiteStructure str = (SiteStructure)JSFUtils.resolveExpression(elexp);
        List<NavigationResource> lstnavresources;
        try {
            if (inputlPageListAllPath != null &&
                inputlPageListAllPath.getValue() != null) {
                String strparentpath =
                    inputlPageListAllPath.getValue().toString();
                String strChuyenmuc =
                    strparentpath.substring(strparentpath.lastIndexOf("/") + 1,
                                            strparentpath.length());
                strparentpath =
                        strparentpath.substring(0, strparentpath.lastIndexOf("/"));
                lstnavresources = str.getResource(strparentpath).getChildren();
                for (NavigationResource nav1 : lstnavresources) {
                    if (nav1.getPrettyUrl().contains(strChuyenmuc)) {
                        strurl = nav1.getPrettyUrl();
                        break;
                    }
                    if (nav1.getChildCount() > 0) {
                        List<NavigationResource> nav2 = nav1.getChildren();
                        for (NavigationResource nav3 : nav2) {
                            if (nav3.getPrettyUrl().contains(strChuyenmuc)) {
                                strurl = nav3.getPrettyUrl();
                                break;
                            }
                            if (nav3.getChildCount() > 0) {
                                for (NavigationResource nav4 :
                                     nav3.getChildren()) {
                                    if (nav4.getPrettyUrl().contains(strChuyenmuc)) {
                                        strurl = nav4.getPrettyUrl();
                                        break;
                                    }
                                }
                            }
                            if (strurl.length() > 0)
                                break;
                        }
                        if (strurl.length() > 0)
                            break;
                    }

                }
            }
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return strurl;
    }

    /**
     * @comment kiem tra xem co anh mo ta hay khong
     * @param dID
     * @return
     * @throws IOException
     * @throws RepositoryException
     * @throws IllegalArgumentException
     * @throws ServletException
     */
    private boolean checkAlternateFileImage(String dID) throws IOException,
                                                               RepositoryException,
                                                               IllegalArgumentException,
                                                               ServletException {

        boolean b = false;
        Property prop = null;
        URLConnection uc = null;
        try {
            ContentContext contentContext;

            contentContext = ContentContextHelper.getContentContext();

            INodeManager nodeManager = ContentManagerFactory.getNodeManager();

            IUCMContext.DocRevisionSelectionMethod revisionSelectionMethod;

            revisionSelectionMethod =
                    IUCMContext.DocRevisionSelectionMethod.LATEST_RELEASED;

            contentContext.setParameter(IUCMContext.DOC_REVISION_SELECTION_METHOD_KEY,
                                        revisionSelectionMethod);

            ID id = ID.fromString(dID);

            Node node = nodeManager.getNodeByUUID(contentContext, id);

            //lay Alternate file


            prop = node.getProperty("idcRenditions");
        } catch (RepositoryException re) {
            // TODO: Add catch code
            re.printStackTrace();
        } catch (Exception ex) {
            // TODO: Add catch code
            ex.printStackTrace();
        }

        if (prop != null) {
            Value vl = prop.getValue();

            //lay noi dung file Alternate
            BinaryValue bnrvl =
                vl.getNestedValue()[0].getValues()[0].getBinaryValue();
            String strvl =
                vl.getNestedValue()[2].getValues()[0].getStringValue();
            URL u = new URL(strvl);
            uc = u.openConnection();

            Object ob = uc.getContent().toString();
            if (uc.getContentType().contains("image/")) {
                b = true;
            }
        }
        return b;
    }

    /**
     * @conmment lay noi dung tu primary file cua tin tuc
     * @param dDocName
     * @return
     * @throws IdcClientException
     * @throws IOException
     */
    private String getDocContent(String dDocName,
                                 String dID) throws IdcClientException,
                                                    IOException {
        String content = null;
        IdcContext userContext = new IdcContext(Global.username);
        DataResultSet drs =
            UtilsContent.getDocInfo(dID, dDocName, Global.getIdcClient(),
                                    userContext);
        if (drs != null) {
            DataObject obj = drs.getRows().get(0);
            String primaryFileFormat = obj.get("dFormat");
            if (primaryFileFormat.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document") ||
                primaryFileFormat.equals("application/msword")) {
                DataBinder dataBinder = Global.getIdcClient().createBinder();

                dataBinder.putLocal("IdcService", "GET_DYNAMIC_CONVERSION");
                dataBinder.putLocal("IsJava", "0");

                dataBinder.putLocal("dDocName", dDocName);
                dataBinder.putLocal("RevisionSelectionMethod",
                                    "LatestReleased");

                ServiceResponse ridc_response;
                ridc_response =
                        Global.getIdcClient().sendRequest(userContext, dataBinder);
                content = ridc_response.getResponseAsString();
                //them webroot vao duong link anh co trong noi dung
                if (content.contains("/cs/groups/"))
                    content =
                            content.replaceAll("/cs/groups/", Global.getWebroot() +
                                               "/cs/groups/");
                if (content.contains("/cs/idcplg"))
                    content =
                            content.replaceAll("/cs/idcplg", Global.getWebroot() +
                                               "/cs/idcplg");
                lstAttachFile = UtilsContent.listAttachfile(dID, dDocName);
            }
        }


        return content;
    }

    /**
     * @creator TuyenNT
     * @comment lay danh sach cac tin khac lien quan
     * @param dDocName : ma noi dung
     * @param numberOfReferent : so luong tin lien quan can hien thi
     * @return
     */
    private List<DataObject> listReferentNews(String dDocName,
                                              int numberOfReferent) {
        List<DataObject> lstdrsr = null;

        try {
            String queryStr = "";
            ValueWrapperImpl vwr =
                (ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['xmChuyenmuctin'].value}");
            String strmuctin = vwr.getStringValue();
            vwr =
(ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['dDocType'].value}");
            String dDocType = vwr.getStringValue();
            vwr =
(ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['xmNgayxuatban'].value}");
            Calendar calNgayxuatban = vwr.getCalendarValue();
            Date xmNgayxuatban = calNgayxuatban.getTime();
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
            //String xmNgayxuatban = vwr.getCalendarValue()
            queryStr =
                    "dDocType <matches> `" + dDocType + "` <AND> xmChuyenmuctin <matches> `" +
                    strmuctin + "` <AND> xmNgayxuatban <= `" +
                    df.format(xmNgayxuatban) +
                    "` <AND> xmHienthi <matches> `True`";
            DataResultSet obj =
                SearchUCMContent(queryStr, "xmNgayxuatban", numberOfReferent,
                                 0, 0, "DESC", Global.getIdcClient(),
                                 Global.getUserContext());
            lstdrsr = obj.getRows();
            CustomizePredicate prdc = new CustomizePredicate();
            prdc.setField("dDocName");
            prdc.setValue(dDocName);
            prdc.setMatch(false);
            CollectionUtils.filter(lstdrsr, prdc);
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }

        return lstdrsr;
    }


    /**
     * @creator
     * @comment Thu tuc tim kiem noi dung trong UCM
     * @param queryString
     * @param sortField
     * @param numberofResult 0: is not set
     * @param startRow 0: is not set
     * @param endRow 0: is not set
     * @param sortOrder ASC, DESC
     * @param client
     * @param userContext
     * @return
     */
    private DataResultSet SearchUCMContent(String queryString,
                                           String sortField,
                                           int numberofResult, int startRow,
                                           int endRow, String sortOrder,
                                           IdcClient client,
                                           IdcContext userContext) {
        DataResultSet obj = null;
        try {
            DataBinder dataBinder = client.createBinder();
            dataBinder.putLocal("IdcService", "GET_SEARCH_RESULTS");
            dataBinder.putLocal("QueryText", queryString);
            dataBinder.putLocal("SortField", sortField);
            //dataBinder.putLocal("PageNumber", Integer.toString(selectedPage));
            //dataBinder.putLocal("SearchEngineName","DATABASE");
            if (numberofResult > 0)
                dataBinder.putLocal("ResultCount",
                                    Integer.toString(numberofResult));
            if (startRow > 0)
                dataBinder.putLocal("StartRow", String.valueOf(startRow));
            if (endRow > 0)
                dataBinder.putLocal("EndRow", String.valueOf(endRow));
            if (sortOrder != null && sortOrder.length() > 0)
                dataBinder.putLocal("SortOrder", sortOrder);
            ServiceResponse ridc_response;
            ridc_response = client.sendRequest(userContext, dataBinder);
            DataBinder binder = ridc_response.getResponseAsBinder();
            totalRows = binder.getLocal("TotalRows");
            obj = binder.getResultSet("SearchResults");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return obj;
    }

    /**
     * @creator
     * @comment doc du lieu cua 1 bang trong csdl UCM
     * @param viewName ten view trong UCM
     * @param tableName ten bang du lieu trong UCM
     * @param client
     * @param userContext
     * @return
     */
    private DataResultSet getViewInfor(String viewName, String tableName,
                                       IdcClient client,
                                       IdcContext userContext) {
        DataResultSet obj = null;
        try {
            DataBinder dataBinder = client.createBinder();
            dataBinder.putLocal("IdcService", "GET_SCHEMA_VIEW_VALUES");
            dataBinder.putLocal("schViewName", viewName.toUpperCase());
            ServiceResponse ridc_response;
            ridc_response = client.sendRequest(userContext, dataBinder);
            DataBinder binder = ridc_response.getResponseAsBinder();
            obj = binder.getResultSet(tableName.toUpperCase());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return obj;
    }

    /**
     * @creator
     * @comment
     * @param expression
     */
    private PresenterConfigurationData readingContentPresenterConfiguration(String expression) {
        PresenterConfigurationData configData = null;
        try {
            SortableModel result =
                (SortableModel)JSFUtils.resolveExpression(expression);
            if (result != null) {
                Object wrapdata = result.getWrappedData();
                if (wrapdata != null) {
                    Field f =
                        result.getClass().getDeclaredField("abstractPresenterBean");
                    f.setAccessible(true);
                    ContentPresenter cntpre = null;
                    PresenterConfiguration configurator =
                        PresenterConfiguration.getInstance();
                    try {
                        cntpre = (ContentPresenter)f.get(result);
                        configData =
                                configurator.getConfigurationData(cntpre.getTaskflowInstanceId(),
                                                                  cntpre.getPageInstance(),
                                                                  false);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    if (cntpre == null) {
                        ContentPresenterWizard cntprewzd =
                            (ContentPresenterWizard)f.get(result);
                        configData =
                                configurator.getConfigurationData(cntprewzd.getTaskflowInstanceId(),
                                                                  cntprewzd.getPageInstance(),
                                                                  true);
                    }


                    //                    if (configData == null) {
                    //                        configData = new PresenterConfigurationData();
                    //                        configData.setInstanceId(cntpre.getTaskflowInstanceId());
                    //                    }

                }
            }
        } catch (IllegalAccessException iae) {
            // TODO: Add catch code
            iae.printStackTrace();
        } catch (IllegalArgumentException iae) {
            // TODO: Add catch code
            iae.printStackTrace();
        } catch (SecurityException se) {
            // TODO: Add catch code
            se.printStackTrace();
        } catch (NoSuchFieldException nsfe) {
            // TODO: Add catch code
            nsfe.printStackTrace();
        } catch (PresenterConfigurationException pce) {
            // TODO: Add catch code
            pce.printStackTrace();
        }
        return configData;
    }

    /**
     * @creator
     * @comment
     * @param expression
     * @return
     */
    private int maxContentPresenterResults(String expression) {
        int maxresult = 0;
        PresenterConfigurationData configData =
            readingContentPresenterConfiguration(expression);
        if (configData != null) {
            ResultsetConfig resultconfig = configData.getResultsetConfig();
            maxresult = resultconfig.getMaxResults();
        }
        return maxresult;

    }

    /**
     * @creator
     * @comment
     * @param expression
     * @return
     */
    private int pagesizeContentPresenterResults(String expression) {
        int pagesize = 0;
        PresenterConfigurationData configData =
            readingContentPresenterConfiguration(expression);
        if (configData != null) {
            ResultsetConfig resultconfig = configData.getResultsetConfig();
            pagesize = resultconfig.getPageSize();
        }
        return pagesize;

    }

    /**
     * @creator
     * @comment
     * @param expression
     * @return
     */
    private QueryDatasource readContentPresenterQuery(String expression) {
        QueryDatasource querydatasource = null;
        PresenterConfigurationData configData =
            readingContentPresenterConfiguration(expression);
        if (configData != null) {
            PresenterDatasource presdatasource = configData.getDatasource();

            querydatasource = presdatasource.getQueryDatasource();
        }
        return querydatasource;
    }

    /**
     * @creator
     * @comment
     * @return
     */
    private String readChuyenmucMucHienthiID() {
        String id = "";
        try {
            QueryDatasource qds = readContentPresenterQuery("#{nodes}");
            if (qds != null) {
                List<SearchCriterion> lstssearch = qds.getSearchCriteria();
                for (SearchCriterion criteria : lstssearch) {
                    if (criteria.getPropertyName().equals("xmMuctinhienthi")) {
                        id = criteria.getStringValue();
                    }
                    if (criteria.getPropertyName().equals("xmChuyenmuctin")) {
                        id = criteria.getStringValue();
                        break;
                    }
                }
            }
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
            id = "";
        }
        return id;
    }

    private String readQueryCondition() {
        String query = "";
        try {
            QueryDatasource qds = readContentPresenterQuery("#{nodes}");
            if (qds != null) {
                List<SearchCriterion> lstssearch = qds.getSearchCriteria();
                for (SearchCriterion criteria : lstssearch) {
                    //                    if(criteria.getComparator().equals("=")){
                    //                        query = " <AND> "
                    //                    }
                    //                    if (criteria.getPropertyName().equals("xmMuctinhienthi")) {
                    //                        id = criteria.getStringValue();
                    //                    }
                    //                    if (criteria.getPropertyName().equals("xmChuyenmuctin")) {
                    //                        id = criteria.getStringValue();
                    //                        break;
                    //                    }
                }
            }
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
            query = "";
        }
        return query;
    }

    /**
     * @creator TuyenNT
     * @comment thu tuc phan trang tin tuc
     * @param selectedPage
     */
    private void getListNewsByKieutinWithPaging(int selectedPage) {
        int startRow = 1;
        try {
            String expression = "#{nodes}";
            //Doc thong tin cau hinh cua content presenter
            // lay so luong tin bai duoc Content Presenter lay ve tren 1 trang
            numberOfResult = maxContentPresenterResults(expression);
            if (numberOfResult > 0) {
                String chuyenmuc;
                // Xac dinh kieu noi tin bai duoc lua chon hien thi
                chuyenmuc = readChuyenmucMucHienthiID();
                List<SearchCriterion> lstSearchCriterion =
                    readContentPresenterQuery(expression).getSearchCriteria();
                String querystring = "";
                querystring +=
                        "dDocType <contains> `Tinbai` <AND> xmNgayxuatban <= `<$dateCurrent(0)$>`  <AND> xmNgayxuatban >`<$dateCurrent(-1825)$>`";
                if (lstSearchCriterion != null) {
                    for (SearchCriterion searchItem : lstSearchCriterion) {
                        String propertyName = searchItem.getPropertyName();
                        String comparator = searchItem.getComparator();
                        String value = searchItem.getStringValue();
                        if (comparator.equals("==") ||
                            comparator.equals("matches"))
                            comparator = "<matches>";
                        if (comparator.equals("like") ||
                            comparator.equals("contains"))
                            comparator = "<contains>";
                        querystring +=
                                " <AND> " + propertyName + " " + comparator +
                                " `" + value + "`";
                    }
                }

                //lay dong bat dau truy van tin bai

                startRow = numberOfResult * (selectedPage - 1) + 1;
                List<SortCriterion> lstsort =
                    readContentPresenterQuery("#{nodes}").getSortCriteria();
                String strSortfield = "xmNgayxuatban";
                String strOrder = "DESC";
                for (SortCriterion sortcri : lstsort) {
                    strSortfield = sortcri.getPropertyName();
                    if (sortcri.isAscending())
                        strOrder = "ASC";
                    break;
                }
                DataResultSet drs =
                    SearchUCMContent(querystring, strSortfield, numberOfResult,
                                     startRow, 0, strOrder,
                                     Global.getIdcClient(),
                                     Global.getUserContext());
                templstNews = drs.getRows();
                int rowscount = 0;
                if (!totalRows.equals("0")) {
                    rowscount = Integer.parseInt(totalRows);
                    numberOfPage =
                            rowscount % numberOfResult > 0 ? (rowscount /
                                                              numberOfResult +
                                                              1) :
                            rowscount / numberOfResult;
                }

                if (pagingPanelBorderLayout.getChildCount() > 0)
                    pagingPanelBorderLayout.getChildren().clear();
                generatePrevLink(selectedPage);
                if (numberOfPage >= 5) {
                    if (selectedPage < numberOfPage)
                        hasnextpage = true;
                    if (selectedPage - 2 >= 0 &&
                        selectedPage + 2 <= numberOfPage) {
                        if (selectedPage - 2 > 1) {
                            //generatePagenumber(1);
                            generateDots("...");
                            //pagesnumber.add("1");
                            // pagesnumber.add("...");

                        }
                        if (selectedPage > 2) {
                            generatePagenumber(selectedPage - 2);
                            //pagesnumber.add(String.valueOf(selectedPage - 2));

                        }
                        generatePagenumber(selectedPage - 1);
                        //pagesnumber.add(String.valueOf(selectedPage - 1));
                        generatePagenumber(selectedPage);
                        //pagesnumber.add(String.valueOf(selectedPage));
                        generatePagenumber(selectedPage + 1);
                        //pagesnumber.add(String.valueOf(selectedPage + 1));
                        generatePagenumber(selectedPage + 2);
                        //pagesnumber.add(String.valueOf(selectedPage + 2));

                        if (selectedPage + 2 < 5) {
                            generatePagenumber(selectedPage + 3);
                            //pagesnumber.add(String.valueOf(selectedPage + 3));
                        }
                        if (selectedPage + 2 < numberOfPage) {
                            generateDots("...");
                            //pagesnumber.add("...");
                            //generatePagenumber(numberOfPage);
                            //pagesnumber.add(String.valueOf(numberOfPage));

                        }

                    } else if (selectedPage < 2) {
                        for (int i = selectedPage; i <= selectedPage + 4;
                             i++) {
                            generatePagenumber(i);
                            //pagesnumber.add(String.valueOf(i));
                        }
                        generateDots("...");
                        //pagesnumber.add("...");
                        //generatePagenumber(numberOfPage);
                        //pagesnumber.add(String.valueOf(numberOfPage));

                    } else if (selectedPage + 2 > numberOfPage) {
                        generatePagenumber(1);
                        //pagesnumber.add("1");
                        generateDots("...");
                        //pagesnumber.add("...");
                        if (selectedPage == numberOfPage)
                            for (int i = selectedPage - 4; i <= selectedPage;
                                 i++) {
                                generatePagenumber(i);
                                //pagesnumber.add(String.valueOf(i));
                            }
                        else
                            for (int i = selectedPage - 3;
                                 i <= selectedPage + 1; i++) {
                                generatePagenumber(i);
                                //pagesnumber.add(String.valueOf(i));
                            }
                    }
                } else {
                    for (int i = 1; i <= numberOfPage; i++) {
                        generatePagenumber(i);
                    }
                    if(numberOfPage >1 && selectedPage < numberOfPage)
                        hasnextpage = true;
                }
                generateNextLink(selectedPage);
            } else
                hasnextpage = false;
           
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * @creator
     * @comment Kiem tra xem tin bai co anh mo ta hay ko?
     * @return
     */
    public boolean checkDecriptionImage() {
        boolean b = false;
        try {
            String strdDocName = "";
            String nodeID = "";
            ValueWrapperImpl dDocName =
                (ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['dDocName'].value}");
            if (dDocName == null) {
                strdDocName =
                        (String)JSFUtils.resolveExpression("#{node.dDocName}");
                nodeID = "/" + Global.getConnectionName() + "/" + strdDocName;
            } else
                nodeID =
                        "/" + Global.getConnectionName() + "/" + dDocName.getStringValue();
            b = checkAlternateFileImage(nodeID);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (RepositoryException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return b;
    }

    /**
     * @creator
     * @comment
     * @param currentpage
     */
    public void generatePrevLink(int currentpage) {
        FacesContext fc = FacesContext.getCurrentInstance();
        Application app = fc.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = fc.getELContext();
        MethodExpression methodExpression =
            elFactory.createMethodExpression(elContext,
                                             "#{contentbean.prevPage}", null,
                                             new Class[] { ActionEvent.class });
        MethodExpressionMethodBinding methodExpressionMethodBinding =
            new MethodExpressionMethodBinding(methodExpression);
        RichCommandLink commandLink = new RichCommandLink();
        //commandLink.setPartialSubmit(true);
        commandLink.setText(getResource("<<_TRUOC"));
        commandLink.getAttributes().put("actionListener",
                                        methodExpressionMethodBinding);
        commandLink.getAttributes().put("prevpage", currentpage - 1);
        commandLink.setInlineStyle("margin-right:5px;");
        if (currentpage < 2)
            commandLink.setDisabled(true);
        else
            commandLink.setDisabled(false);
        pagingPanelBorderLayout.getChildren().add(commandLink);
    }

    /**
     * @creator
     * @comment
     * @param currentpage
     */
    public void generateNextLink(int currentpage) {
        FacesContext fc = FacesContext.getCurrentInstance();
        Application app = fc.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = fc.getELContext();
        MethodExpression methodExpression =
            elFactory.createMethodExpression(elContext,
                                             "#{contentbean.nextPage}", null,
                                             new Class[] { ActionEvent.class });
        MethodExpressionMethodBinding methodExpressionMethodBinding =
            new MethodExpressionMethodBinding(methodExpression);
        RichCommandLink commandLink = new RichCommandLink();
        //commandLink.setPartialSubmit(true);
        commandLink.setText(getResource("SAU_>>"));
        commandLink.getAttributes().put("actionListener",
                                        methodExpressionMethodBinding);
        commandLink.getAttributes().put("nexpage", currentpage + 1);
        commandLink.setInlineStyle("margin-left:5px;");
        if (!hasnextpage)
            commandLink.setDisabled(true);
        pagingPanelBorderLayout.getChildren().add(commandLink);
    }

    /**
     * @creator
     * @comment
     * @param pagenumber
     */
    public void generatePagenumber(int pagenumber) {
        FacesContext fc = FacesContext.getCurrentInstance();
        Application app = fc.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = fc.getELContext();
        MethodExpression methodExpression =
            elFactory.createMethodExpression(elContext,
                                             "#{contentbean.pageSeleted}",
                                             null,
                                             new Class[] { ActionEvent.class });
        MethodExpressionMethodBinding methodExpressionMethodBinding =
            new MethodExpressionMethodBinding(methodExpression);
        RichCommandLink commandLink = new RichCommandLink();
        //commandLink.setPartialSubmit(true);
        commandLink.setText(String.valueOf(pagenumber));
        if (pagenumber == selectedPage)
            commandLink.setInlineStyle("font-weight:bold; margin:0 2px;");
        else
            commandLink.setInlineStyle("margin:0 2px;");

        //commandLink.setActionExpression(methodExpression);
        commandLink.getAttributes().put("actionListener",
                                        methodExpressionMethodBinding);
        commandLink.getAttributes().put("selectedpage", pagenumber);
        pagingPanelBorderLayout.getChildren().add(commandLink);
    }

    /**
     * @creator
     * @comment
     * @param value
     */
    public void generateDots(String value) {
        FacesContext fc = FacesContext.getCurrentInstance();
        Application app = fc.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = fc.getELContext();
        RichOutputText ouputtext = new RichOutputText();
        ouputtext.setValue(value);
        pagingPanelBorderLayout.getChildren().add(ouputtext);
    }

    /**
     * @creator
     * @comment
     * @param dID
     * @param dDocName
     */
    private void listAttachfile(String dID, String dDocName) {
        DataResultSet drs =
            UtilsContent.getAttachfilesInfo(dID, dDocName, Global.getIdcClient(),
                                            Global.getUserContext());
        lstAttachFile = drs.getRows();
    }

    protected boolean isPostback() {
        return Boolean.TRUE.equals(oracle.webcenter.framework.service.JSFUtils.resolveExpression("#{adfFacesContext.postback}"));
    }

    private String getResource(String resourceKey) {

        ResourceBundle bundle =
            ResourceBundle.getBundle("portal.PortalBundle", LocaleBean.getCurrentInstance().getUserLocale());
        return bundle.getString(resourceKey);
    }

    /**
     * @creator
     * @comment
     */
    private void listlimitedcontents() {
        String querystring = "";
        String elExpress = "#{nodes}";
        numberOfResult = maxContentPresenterResults(elExpress);
        List<SearchCriterion> lstSearchCriterion =
            readContentPresenterQuery(elExpress).getSearchCriteria();
        querystring += "xmNgayxuatban <= `<$dateCurrent(0)$>` ";
        if (lstSearchCriterion != null) {
            for (SearchCriterion searchItem : lstSearchCriterion) {
                String propertyName = searchItem.getPropertyName();
                String comparator = searchItem.getComparator();
                String value = searchItem.getStringValue();
                if (comparator.equals("==") || comparator.equals("matches"))
                    comparator = "<matches>";
                if (comparator.equals("like") || comparator.equals("contains"))
                    comparator = "<contains>";
                querystring +=
                        " <AND> " + propertyName + " " + comparator + " `" +
                        value + "`";
            }
        }

        List<SortCriterion> lstsort =
            readContentPresenterQuery("#{nodes}").getSortCriteria();
        String strSortfield = "xmNgayxuatban";
        String strOrder = "DESC";
        for (SortCriterion sortcri : lstsort) {
            strSortfield = sortcri.getPropertyName();
            if (sortcri.isAscending())
                strOrder = "ASC";
            break;
        }
        DataResultSet drs =
            SearchUCMContent(querystring, strSortfield, numberOfResult, 0, 0,
                             strOrder, Global.getIdcClient(),
                             Global.getUserContext());
        templstNews = drs.getRows();
        if (templstNews.size() > 1) {
            templst2x = true;
        } else {
            templst2x = false;
        }
        if (templstNews.size() > 2) {
            templst2x2 = true;
        } else {
            templst2x2 = false;
        }
    }

    private void listLienKetGroup() {
        lstLienketGroup =
                UtilsContent.getViewInfor("UBCK_NHOMLIENKET_VIEW", "UBCK_NHOMLIENKET",
                                          Global.getIdcClient(),
                                          Global.getUserContext()).getRows();
        CustomizeDataObjectPredicate prdc = new CustomizeDataObjectPredicate();
        prdc.setField("NGONNGU");
        prdc.setValue(LocaleBean.getCurrentInstance().getLanguage());
        prdc.setMatch(true);
        CollectionUtils.filter(lstLienketGroup, prdc);
    }

    private void listLienketbyGroup(String groupID) {
        String query =
            "dDocType <contains> `Lienketweb` <AND> xmHienthi <contains> `True`" +
            " <AND> xmNhomlienket <matches> `" + groupID +
            "` <AND> xmNgonngu <matches> `" +
            LocaleBean.getCurrentInstance().getLanguage() + "`";
        lstLienket.clear();
        lstLienket =
                SearchUCMContent(query, "dDocTitle", 0, 0, 0, "ASC", Global.getIdcClient(),
                                 Global.getUserContext()).getRows();
    }


    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getCurrentPage() {
        currentPage = selectedPage;
        return currentPage;
    }

    public void setTemplstNews(List<DataObject> templstNews) {
        this.templstNews = templstNews;
    }

    public List<DataObject> getTemplstNews() {
        //if (!functionrequest.contains("getTemplstNews")) {
        //getListNewsByKieutinWithPaging(selectedPage);
        //functionrequest += "getTemplstNews;";
        //}
        //listlimitedcontents();
        return templstNews;
    }

    public void setPagesnumber(List<String> pagesnumber) {
        this.pagesnumber = pagesnumber;
    }

    public List<String> getPagesnumber() {
        if (UtilsContent.getPageFlowScope("pagesnumber") != null)
            pagesnumber =
                    (List<String>)UtilsContent.getPageFlowScope("pagesnumber");
        if (pagesnumber.size() == 1)
            pagesnumber.clear();
        return pagesnumber;
    }

    public void setNumberOfPage(int numberOfPage) {
        this.numberOfPage = numberOfPage;
    }

    public int getNumberOfPage() {
        return numberOfPage;
    }


    public void setSelectedPage(int selectedPage) {
        this.selectedPage = selectedPage;
    }

    public int getSelectedPage() {
        return selectedPage;
    }


    public void setNumberOfResult(int numberOfResult) {
        this.numberOfResult = numberOfResult;
    }

    public int getNumberOfResult() {
        return numberOfResult;
    }

    public void setCounter(int counter) {
        this.counter = counter;
    }

    public int getCounter() {
        if (counter == 3)
            counter = 0;
        return counter;
    }

    public void setNgayxuatban(Date ngayxuatban) {
        this.ngayxuatban = ngayxuatban;
    }

    public Date getNgayxuatban() {
        try {
            String day;
            ValueWrapperImpl vwrp =
                (ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['xmNgayxuatban'].value}");
            if (vwrp == null) {
                day =
JSFUtils.resolveExpression("#{node.xmNgayxuatban}").toString();
                SimpleDateFormat format =
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:SS",
                                         LocaleBean.getCurrentInstance().getUserLocale());
                ngayxuatban = format.parse(day);
                format =
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:SS", LocaleBean.getCurrentInstance().getUserLocale());
                day = format.format(ngayxuatban);
                ngayxuatban = format.parse(day);
                Calendar cal = Calendar.getInstance();
                cal.setTimeZone(timezone);
                cal.setTime(ngayxuatban);
                cal.add(cal.HOUR, 7);
                ngayxuatban = cal.getTime();
            } else {
                Calendar strNgayxuatban = vwrp.getCalendarValue();
                ngayxuatban = strNgayxuatban.getTime();
            }
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }

        return ngayxuatban;
    }

    public void setChuyenmuctin(String chuyenmuctin) {
        this.chuyenmuctin = chuyenmuctin;
    }

    public String getChuyenmuctin() {

        try {
            //            ValueWrapperImpl vwrp =
            //                (ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['xmChuyenmuctin'].value}");
            //            chuyenmuctinID = vwrp.getStringValue();
            chuyenmuctinID = readChuyenmucMucHienthiID();
            if (chuyenmuctinID.equals("")) {
                ValueWrapperImpl vwrp =
                    (ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['xmChuyenmuctin'].value}");
                chuyenmuctinID = vwrp.getStringValue();
            }
            List<DataObject> lstchuyenmuc = UtilsContent.getdschuyenmuctin();
            if (lstchuyenmuc != null) {
                for (DataObject dtobj : lstchuyenmuc) {
                    if (dtobj.get("ID").equals(chuyenmuctinID)) {
                        chuyenmuctin = dtobj.get("CHUYENMUC");
                        break;
                    }
                }
            }
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        //lay duong dan trang chi tiet
        //pagedetailUrl = detailPageUrl();
        //lay duong dan trang danh sach xem tat ca

        return chuyenmuctin;
    }

    public void setChuyenmuctinID(String chuyenmuctinID) {
        this.chuyenmuctinID = chuyenmuctinID;
    }

    public String getChuyenmuctinID() {
        chuyenmuctinID = readChuyenmucMucHienthiID();
        return chuyenmuctinID;
    }

    public void setIteratorNodes(UIXIterator iteratorNodes) {
        this.iteratorNodes = iteratorNodes;
        //getListNewsByKieutinWithPaging(selectedPage);
    }

    public UIXIterator getIteratorNodes() {
        return iteratorNodes;
    }

    public void setHasnextpage(boolean hasnextpage) {
        this.hasnextpage = hasnextpage;
    }

    public boolean isHasnextpage() {
        if (UtilsContent.getPageFlowScope("hasnextpage") != null)
            hasnextpage =
                    (Boolean)UtilsContent.getPageFlowScope("hasnextpage");
        return hasnextpage;
    }

    public void setPagingPanelBorderLayout(RichPanelBorderLayout pagingPanelBorderLayout) {
        this.pagingPanelBorderLayout = pagingPanelBorderLayout;
    }

    public RichPanelBorderLayout getPagingPanelBorderLayout() {
        return pagingPanelBorderLayout;
    }

    public void prevPage(ActionEvent actionEvent) {
        selectedPage =
                Integer.parseInt(actionEvent.getComponent().getAttributes().get("prevpage").toString());
        getListNewsByKieutinWithPaging(selectedPage);
        //AdfFacesContext.getCurrentInstance().addPartialTarget(vbckTable);
        AdfFacesContext.getCurrentInstance().addPartialTarget(pagingPanelBorderLayout);
    }

    public void pageSeleted(ActionEvent actionEvent) {
        selectedPage =
                Integer.parseInt(actionEvent.getComponent().getAttributes().get("selectedpage").toString());
        getListNewsByKieutinWithPaging(selectedPage);
        //AdfFacesContext.getCurrentInstance().addPartialTarget(vbckTable);
        AdfFacesContext.getCurrentInstance().addPartialTarget(pagingPanelBorderLayout);
    }

    public void nextPage(ActionEvent actionEvent) {
        selectedPage =
                Integer.parseInt(actionEvent.getComponent().getAttributes().get("nexpage").toString());
        getListNewsByKieutinWithPaging(selectedPage);
        //        AdfFacesContext.getCurrentInstance().addPartialTarget(vbckTable);
        AdfFacesContext.getCurrentInstance().addPartialTarget(pagingPanelBorderLayout);
    }

    public void setInputDetailPath(RichInputText inputDetailPath) {
        this.inputDetailPath = inputDetailPath;
    }

    public RichInputText getInputDetailPath() {
        //pagedetailUrl = detailPageUrl();
        return inputDetailPath;
    }

    public void setInputlPageListAllPath(RichInputText inputlPageListAllPath) {
        this.inputlPageListAllPath = inputlPageListAllPath;
    }

    public RichInputText getInputlPageListAllPath() {
        return inputlPageListAllPath;
    }

    public void setPageListAllUrl(String pageListAllUrl) {
        this.pageListAllUrl = pageListAllUrl;
    }

    public String getPageListAllUrl() {
        pageListAllUrl = listAllPageUrl();
        return pageListAllUrl;
    }

    public void setCurrentrequestURL(String currentrequestURL) {
        this.currentrequestURL = currentrequestURL;
    }

    public String getCurrentrequestURL() {
        currentrequestURL = currentRequestUrl();
        return currentrequestURL;
    }

    public void setIndividualpagedetailUrl(String individualpagedetailUrl) {

        this.individualpagedetailUrl = individualpagedetailUrl;
    }

    public String getIndividualpagedetailUrl() {
        individualpagedetailUrl = detailPageUrl();
        return individualpagedetailUrl;
    }

    public void setTimezone(TimeZone timezone) {
        this.timezone = timezone;
    }

    public TimeZone getTimezone() {
        return timezone;
    }

    public void setLstAttachFile(List<DataObject> lstAttachFile) {
        this.lstAttachFile = lstAttachFile;
    }

    public List<DataObject> getLstAttachFile() {
        return lstAttachFile;
    }

    public void setHasAttachFile(boolean hasAttachFile) {
        this.hasAttachFile = hasAttachFile;
    }

    public boolean isHasAttachFile() {
        if (lstAttachFile.size() > 0)
            hasAttachFile = true;
        return hasAttachFile;
    }

    public void setInitListContent(String initListContent) {
        this.initListContent = initListContent;
    }

    public String getInitListContent() {
        listlimitedcontents();
        return initListContent;
    }

    public void setLstLienketGroup(List<DataObject> lstLienketGroup) {
        this.lstLienketGroup = lstLienketGroup;
    }

    public List<DataObject> getLstLienketGroup() {
        if (!isPostback()) {
            listLienKetGroup();
        }
        return lstLienketGroup;
    }

    public void setLstLienket(List<DataObject> lstLienket) {
        this.lstLienket = lstLienket;
    }

    public List<DataObject> getLstLienket() {
        if (!isPostback()) {
            Object vwrp = (Object)JSFUtils.resolveExpression("#{node.ID}");
            String id = vwrp.toString();
            if (id != null) {
                listLienketbyGroup(id);
            }
        }
        return lstLienket;
    }

    public void setInputGroupID(RichInputText inputGroupID) {
        this.inputGroupID = inputGroupID;
    }

    public RichInputText getInputGroupID() {
        return inputGroupID;
    }

    public void setHasOldDicriptionImage(boolean hasOldDicriptionImage) {
        this.hasOldDicriptionImage = hasOldDicriptionImage;
    }

    public boolean isHasOldDicriptionImage() {
        hasOldDicriptionImage = checkDecriptionImage();
        return hasOldDicriptionImage;
    }

    public void setTemplst2x2(boolean templst2x2) {
        this.templst2x2 = templst2x2;
    }

    public boolean isTemplst2x2() {
        return templst2x2;
    }

    public void setTemplst2x(boolean templst2x) {
        this.templst2x = templst2x;
    }

    public boolean isTemplst2x() {
        return templst2x;
    }


    /**
     * @creator
     * @comment
     */
    public static class CustomizePredicate implements Predicate {
        private String field;
        private Object value;
        private boolean match;

        public boolean evaluate(Object object) {
            if (object instanceof DataResultSetRow) {
                DataResultSetRow ob = (DataResultSetRow)object;
                return value.equals(ob.get(field)) == match;
            }
            return false;
        }

        public void setField(String field) {
            this.field = field;
        }

        public String getField() {
            return field;
        }

        public void setValue(Object value) {
            this.value = value;
        }

        public Object getValue() {
            return value;
        }

        public void setMatch(boolean match) {
            this.match = match;
        }

        public boolean isMatch() {
            return match;
        }
    }

    public static class CustomizeDataObjectPredicate implements Predicate {
        private String field;
        private Object value;
        private boolean match;

        public boolean evaluate(Object object) {
            if (object instanceof DataObject) {
                DataObject ob = (DataObject)object;
                return value.equals(ob.get(field)) == match;
            }
            return false;
        }

        public void setField(String field) {
            this.field = field;
        }

        public String getField() {
            return field;
        }

        public void setValue(Object value) {
            this.value = value;
        }

        public Object getValue() {
            return value;
        }

        public void setMatch(boolean match) {
            this.match = match;
        }

        public boolean isMatch() {
            return match;
        }
    }

    public void setLstObjectNode(SortableModel lstObjectNode) {
        this.lstObjectNode = lstObjectNode;
    }

    public SortableModel getLstObjectNode() {
        lstObjectNode = listObjecNode("dInDate", false);
        return lstObjectNode;
    }

    public void setImgcontent(String imgcontent) {
        this.imgcontent = imgcontent;
    }

    public String getImgcontent() {

        return imgcontent;
    }

    public void setConnectionName(String connectionName) {
        this.connectionName = connectionName;
    }

    public String getConnectionName() {

        connectionName = Global.getConnectionName();

        return connectionName;
    }


    public void setTempara(String tempara) {
        this.tempara = tempara;
    }

    public String getTempara() {
        getListNewsByKieutinWithPaging(selectedPage);
        //listlimitedcontents();
        return tempara;
    }

    public void setPagedetailUrl(String pagedetailUrl) {
        this.pagedetailUrl = pagedetailUrl;
    }

    public String getPagedetailUrl() {
        return pagedetailUrl;
    }

    public void setHasDicriptionImage(boolean hasDicriptionImage) {
        this.hasDicriptionImage = hasDicriptionImage;
    }

    public boolean isHasDicriptionImage() {

        String dDocName =
            (String)UtilsContent.getValueExpression("#{node.dDocName}");
        String anhMoTaDDocName =
            UtilsContent.contentMetaDataInfo(dDocName, "xmAnhmota");
        if (anhMoTaDDocName != null && !anhMoTaDDocName.isEmpty())
            hasDicriptionImage = true;
        else {

            hasDicriptionImage = false;
        }
        return hasDicriptionImage;
    }

    public void setNewscontent(String newscontent) {
        this.newscontent = newscontent;
    }

    public String getNewscontent() {

        ValueWrapperImpl vwrp =
            (ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['dDocName'].value}");
        String dDocName = vwrp.getStringValue();
        vwrp =
(ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['dID'].value}");
        String dID = vwrp.getStringValue();
        try {
            newscontent = getDocContent(dDocName, dID);
            functionrequest += "getNewscontent;";
        } catch (IdcClientException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return newscontent;
    }

    public void setLstReferentNodes(List<DataObject> lstReferentNodes) {
        this.lstReferentNodes = lstReferentNodes;
    }

    public List<DataObject> getLstReferentNodes() {
        ValueWrapperImpl vwrp =
            (ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['dDocName'].value}");
        String dDocName = vwrp.getStringValue();
        lstReferentNodes = listReferentNews(dDocName, 10);
        //        for(DataObject dtobj:lstReferentNodes) {
        //            Calendar d = dtobj.getCalendar("xmNgayxuatban");
        //            dtobj.setDate("xmNgayxuatban", d.getTime());
        //            String s="";
        //        }
        return lstReferentNodes;
    }

    public void setNewsDetailTitle(String newsDetailTitle) {
        this.newsDetailTitle = newsDetailTitle;
    }

    public String getNewsDetailTitle() {

        DataResultSet drs =
            getViewInfor("CHUYENMUCTIN_VIEW", "CHUYENMUCTIN", Global.getIdcClient(),
                         Global.getUserContext());
        ValueWrapperImpl vwrp =
            (ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['xmChuyenmuctin'].value}");
        String kieutintuc = vwrp.getStringValue();
        for (Object Obj : drs.getRows()) {
            if (Obj instanceof DataResultSetRow) {
                DataResultSetRow drsrContent = (DataResultSetRow)Obj;
                if (kieutintuc.contains(drsrContent.get("ID").toString())) {
                    newsDetailTitle = drsrContent.get("CHUYENMUC");
                    break;
                }

            }
        }
        return newsDetailTitle;
    }

    public void setLstNews(SortableModel lstNews) {
        this.lstNews = lstNews;
    }

    public SortableModel getLstNews() {
        lstNews = listObjecNode("", false);
        return lstNews;
    }
}
